package com.campus.secondhand.service.impl;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.context.annotation.Lazy;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.campus.secondhand.common.Result;
import com.campus.secondhand.entity.Favorites;
import com.campus.secondhand.entity.User;
import com.campus.secondhand.mapper.FavoriteMapper;
import com.campus.secondhand.model.vo.ProductDetailVO;
import com.campus.secondhand.model.vo.ProductListVO;
import com.campus.secondhand.model.vo.PurchaseRequestVO;
import com.campus.secondhand.model.vo.PurchaseRequestDetailVO;
import com.campus.secondhand.service.FavoriteService;
import com.campus.secondhand.service.ProductService;
import com.campus.secondhand.service.PurchaseRequestService;
import com.campus.secondhand.service.UserService;
import com.campus.secondhand.model.vo.UserSimpleVO;

import lombok.extern.slf4j.Slf4j;

/**
 * 收藏服务实现类
 */
@Service
@Slf4j
public class FavoriteServiceImpl extends ServiceImpl<FavoriteMapper, Favorites> implements FavoriteService {

    private final ProductService productService;
    private final UserService userService;
    private final PurchaseRequestService purchaseRequestService;

    public FavoriteServiceImpl(@Lazy ProductService productService,
            UserService userService,
            @Lazy PurchaseRequestService purchaseRequestService) {
        this.productService = productService;
        this.userService = userService;
        this.purchaseRequestService = purchaseRequestService;
    }

    /**
     * 判断用户是否已收藏商品
     */
    @Override
    public Boolean isFavorite(Long userId, Long productId) {
        if (userId == null || productId == null) {
            return false;
        }

        LambdaQueryWrapper<Favorites> queryWrapper = Wrappers.lambdaQuery(Favorites.class)
                .eq(Favorites::getUserId, userId)
                .eq(Favorites::getProductId, productId);

        return count(queryWrapper) > 0;
    }

    /**
     * 判断用户是否已收藏求购信息
     */
    @Override
    public Boolean isPurchaseRequestFavorite(Long userId, Long purchaseRequestId) {
        if (userId == null || purchaseRequestId == null) {
            return false;
        }

        LambdaQueryWrapper<Favorites> queryWrapper = Wrappers.lambdaQuery(Favorites.class)
                .eq(Favorites::getUserId, userId)
                .eq(Favorites::getPurchaseRequestId, purchaseRequestId);

        return count(queryWrapper) > 0;
    }

    /**
     * 获取商品的收藏数量
     */
    @Override
    public Integer countProductFavorites(Long productId) {
        if (productId == null) {
            return 0;
        }

        LambdaQueryWrapper<Favorites> queryWrapper = Wrappers.lambdaQuery(Favorites.class)
                .eq(Favorites::getProductId, productId);

        return Math.toIntExact(count(queryWrapper));
    }

    /**
     * 获取求购信息的收藏数量
     */
    @Override
    public Integer countPurchaseRequestFavorites(Long purchaseRequestId) {
        if (purchaseRequestId == null) {
            return 0;
        }

        LambdaQueryWrapper<Favorites> queryWrapper = Wrappers.lambdaQuery(Favorites.class)
                .eq(Favorites::getPurchaseRequestId, purchaseRequestId);

        return Math.toIntExact(count(queryWrapper));
    }

    /**
     * 添加商品收藏
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> addFavorite(Long userId, Long productId) {

        // 验证用户是否存在
        User user = userService.getUserById(userId);
        if (user == null) {
            return Result.error(404, "用户不存在");
        }

        // 检查商品是否存在
        Result<ProductDetailVO> productResult = productService.getProductDetail(productId, userId);
        if (productResult.getCode() != 200 || productResult.getData() == null) {
            return Result.error(404, "商品不存在");
        }

        // 检查是否已收藏
        if (isFavorite(userId, productId)) {
            return Result.error(400, "已收藏该商品");
        }

        // 创建收藏记录
        Favorites favorites = new Favorites();
        favorites.setUserId(userId);
        favorites.setProductId(productId);
        favorites.setPurchaseRequestId(null); // 确保求购ID为空
        favorites.setCreatedAt(LocalDateTime.now());

        // 保存收藏
        boolean success = save(favorites);

        if (!success) {
            return Result.error("收藏失败");
        }

        return Result.success(null, "收藏成功");
    }

    /**
     * 添加求购信息收藏
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> addPurchaseRequestFavorite(Long userId, Long purchaseRequestId) {
        // 验证用户是否存在
        User user = userService.getUserById(userId);
        if (user == null) {
            return Result.error(404, "用户不存在");
        }

        // 检查求购信息是否存在
        Result<?> requestResult = purchaseRequestService.getRequestDetail(purchaseRequestId);
        if (requestResult.getCode() != 200 || requestResult.getData() == null) {
            return Result.error(404, "求购信息不存在");
        }

        // 检查是否已收藏
        if (isPurchaseRequestFavorite(userId, purchaseRequestId)) {
            return Result.error(400, "已收藏该求购信息");
        }

        // 创建收藏记录
        Favorites favorites = new Favorites();
        favorites.setUserId(userId);
        favorites.setProductId(null); // 确保商品ID为空
        favorites.setPurchaseRequestId(purchaseRequestId);
        favorites.setCreatedAt(LocalDateTime.now());

        // 保存收藏
        boolean success = save(favorites);

        if (!success) {
            return Result.error("收藏失败");
        }

        return Result.success(null, "收藏成功");
    }

    /**
     * 取消商品收藏
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> removeFavorite(Long userId, Long productId) {
        // 检查是否已收藏
        if (!isFavorite(userId, productId)) {
            return Result.error(400, "未收藏该商品");
        }

        // 构建删除条件
        LambdaQueryWrapper<Favorites> queryWrapper = Wrappers.lambdaQuery(Favorites.class)
                .eq(Favorites::getUserId, userId)
                .eq(Favorites::getProductId, productId);

        // 删除收藏
        boolean success = remove(queryWrapper);

        if (!success) {
            return Result.error("取消收藏失败");
        }

        return Result.success(null, "取消收藏成功");
    }

    /**
     * 取消求购信息收藏
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> removePurchaseRequestFavorite(Long userId, Long purchaseRequestId) {
        // 检查是否已收藏
        if (!isPurchaseRequestFavorite(userId, purchaseRequestId)) {
            return Result.error(400, "未收藏该求购信息");
        }

        // 构建删除条件
        LambdaQueryWrapper<Favorites> queryWrapper = Wrappers.lambdaQuery(Favorites.class)
                .eq(Favorites::getUserId, userId)
                .eq(Favorites::getPurchaseRequestId, purchaseRequestId);

        // 删除收藏
        boolean success = remove(queryWrapper);

        if (!success) {
            return Result.error("取消收藏失败");
        }

        return Result.success(null, "取消收藏成功");
    }

    /**
     * 获取用户的收藏商品列表
     */
    @Override
    public Result<Page<ProductListVO>> getUserFavorites(Long userId, Pageable pageable) {
        // 分页查询用户收藏
        int page = pageable.getPageNumber();
        int size = pageable.getPageSize();

        // 查询用户收藏的商品ID列表
        LambdaQueryWrapper<Favorites> queryWrapper = Wrappers.lambdaQuery(Favorites.class)
                .eq(Favorites::getUserId, userId)
                .isNotNull(Favorites::getProductId) // 确保只查询商品收藏
                .orderByDesc(Favorites::getCreatedAt);

        // 先计算总数
        long total = count(queryWrapper);

        List<Favorites> favorites = list(queryWrapper);

        // 获取商品ID列表
        List<Long> productIds = favorites.stream()
                .map(Favorites::getProductId)
                .collect(Collectors.toList());

        if (productIds.isEmpty()) {
            return Result.success(new PageImpl<>(new ArrayList<>(), pageable, 0), "获取成功");
        }

        // 创建结果集合
        List<ProductListVO> productVOs = new ArrayList<>();

        // 获取商品列表
        // 这里我们需要调用getProductList来获取ProductListVO，因为getProductDetail返回的是ProductDetailVO
        Result<Page<ProductListVO>> productsResult = productService.getProductList(
                null, null, null, null, null,
                "createdAt", "desc", null, null, pageable, userId);

        if (productsResult.getCode() == 200 && productsResult.getData() != null) {
            // 过滤出收藏的商品
            List<ProductListVO> allProducts = productsResult.getData().getContent();
            for (ProductListVO product : allProducts) {
                if (productIds.contains(product.getId())) {
                    productVOs.add(product);
                }
            }
        }

        // 创建分页结果
        Page<ProductListVO> result = new PageImpl<>(productVOs, pageable, total);

        return Result.success(result, "获取成功");
    }

    /**
     * 获取用户的收藏求购信息列表
     */
    @Override
    public Result<Page<PurchaseRequestVO>> getUserFavoritePurchaseRequests(Long userId, Pageable pageable) {

        // 查询用户收藏的求购信息ID列表
        LambdaQueryWrapper<Favorites> queryWrapper = Wrappers.lambdaQuery(Favorites.class)
                .eq(Favorites::getUserId, userId)
                .isNotNull(Favorites::getPurchaseRequestId) // 确保只查询求购信息收藏
                .orderByDesc(Favorites::getCreatedAt);

        List<Favorites> favorites = list(queryWrapper);

        // 获取求购信息ID列表
        List<Long> requestIds = favorites.stream()
                .map(Favorites::getPurchaseRequestId)
                .collect(Collectors.toList());

        if (requestIds.isEmpty()) {
            return Result.success(new PageImpl<>(new ArrayList<>(), pageable, 0), "获取成功");
        }

        // 获取所有收藏的求购信息（不进行分页）
        List<PurchaseRequestVO> favoriteRequests = new ArrayList<>();

        // 遍历收藏ID，查询每个求购信息
        for (Long requestId : requestIds) {
            Result<PurchaseRequestDetailVO> requestResult = purchaseRequestService.getRequestDetail(requestId);
            if (requestResult.getCode() == 200 && requestResult.getData() != null) {
                // 将DetailVO转换为普通VO
                PurchaseRequestDetailVO detailVO = requestResult.getData();
                PurchaseRequestVO vo = new PurchaseRequestVO();
                // 设置基本属性（根据实际VO结构）
                vo.setId(detailVO.getId());
                vo.setTitle(detailVO.getTitle());
                vo.setDescription(detailVO.getDescription());
                vo.setBudget(detailVO.getBudget());
                vo.setCategoryId(detailVO.getCategoryId());
                vo.setCategoryName(detailVO.getCategoryName());
                vo.setTime(detailVO.getFormatTime());
                vo.setViews(detailVO.getViews());
                vo.setStatus(detailVO.getStatus());

                // 设置用户信息
                if (detailVO.getUser() != null) {
                    UserSimpleVO userSimpleVO = new UserSimpleVO();
                    userSimpleVO.setId(detailVO.getUser().getId());
                    userSimpleVO.setName(detailVO.getUser().getName());
                    userSimpleVO.setAvatar(detailVO.getUser().getAvatar());
                    userSimpleVO.setSchool(detailVO.getUser().getSchool());
                    vo.setUser(userSimpleVO);
                }

                vo.setIsFavorite(true); // 设置为已收藏
                favoriteRequests.add(vo);
            }
        }

        // 创建Page对象包含所有数据
        Page<PurchaseRequestVO> resultPage = new PageImpl<>(favoriteRequests, pageable, favoriteRequests.size());
        return Result.success(resultPage, "获取成功");
    }
}